import {
    AfterViewChecked,
    Component,
    OnInit,
    EventEmitter,
    Injector,
    Output,
    ViewChild,
    ViewContainerRef,
    ComponentRef,
    ViewEncapsulation
} from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    MainTaskServiceProxy,
    MainTaskGoProductionDto,
    BatchBoundTechDocInput,
    ReceiveTaskInput,
    TaskDto,
    NameValueDtoOfNameValueDto,
    PipelineServiceProxy,
    PipelineNodesServiceProxy,
    OrganizationUnitServiceProxy,
    TechDocServiceProxy,
    PipelineListDto,
    SimpleTechDocDto,
    TechDocDto,
    BatchBoundTech,
    StationDto,
    NodeEquipmentDto,
    GetNodeWorkOutput,
    NameValueDto,
    EquipmentServiceProxy,
    NodeWorkerDto,
    ProcViewDto,
    SetNodeWorkersInput,
    SetNodeEquipmentsInput,
    GetNodeWorkOutputOfBatch,
    BatchSetInput
} from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { MenuItem } from 'primeng/api';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import * as moment from 'moment';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import { ComboboxItemDto } from '@shared/service-proxies/ztdevice-service-proxies';
import { Key } from 'selenium-webdriver';
import { element } from '@angular/core/src/render3';
import { ifError } from 'assert';

@Component({
    selector: 'batchIntoReportModal',
    styleUrls: ['./batch-into-report.component.less'],
    templateUrl: './batch-into-report.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class BatchIntoReportComponent  extends AppComponentBase implements OnInit  {
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('selectpaginator') selectpaginator: Paginator;
    @ViewChild('taskdataTable') taskdataTable: Table;
    @ViewChild('selectdataTable') selectdataTable: Table;
    @ViewChild('container', { read: ViewContainerRef })
    container: ViewContainerRef;

    compRef: ComponentRef<any>; //  加载的组件实例
    selectPrimengTableHelper: PrimengTableHelper;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    type = 1;
    filterText = '';
    active = false;
    saving = false;
    runing = false;
    selected: any[];
    selected1: any[];
    receiveTasks = new Array<ReceiveTaskInput>();
    dueDate = new Date();
    procInfo = new ProcViewDto();
    order: TaskDto = new TaskDto();
    mainTaskGoProductionList = new Array<MainTaskGoProductionDto>();
    Outsourcings;
    cols: any[];
    tmpls: NameValueDtoOfNameValueDto[];
    tmplName = '';
    pipe = new PipelineListDto();
    pipeId: string;
    techDocs = new Array<SimpleTechDocDto>();
    selectedTechDoc = new SimpleTechDocDto();
    setNodeEquipments = new SetNodeEquipmentsInput();
    techDocView = new TechDocDto();
    oldTechDocView = new TechDocDto();
    pipeNodeId = '';
    teamGroups: ComboboxItemDto[] = [];
    teamGroupName = '';
    data: any[];
    pipes = new Array<PipelineListDto>();
    pipes1 = new Array<PipelineListDto>();
    stationId = 0;
    station = new StationDto();
    stations = new Array<StationDto>();
    equipments = new Array<NodeEquipmentDto>();
    shebei: ComboboxItemDto[];
    selectshebei: ComboboxItemDto[];
    nodeWorker = new Array<GetNodeWorkOutput>();
    tabs: MenuItem[];
    nodeWorker1 = new GetNodeWorkOutputOfBatch();
    index = 1;
    setNodeWorkers = new SetNodeWorkersInput();
    setNodeWorkers1 = new Array<SetNodeWorkersInput>();
    newCar: boolean;
    pipeIds: string[];
    pipeIds1: string[];
    displayDialog: boolean;
    selectedWork = new GetNodeWorkOutput();
    users = new Array<NameValueDto>();
    constructor(
        injector: Injector,

        private _mainTaskServiceProxy: MainTaskServiceProxy,
        private _pipelineService: PipelineServiceProxy,
        private _taskServiceProxy: PipelineNodesServiceProxy,
        private _organization: OrganizationUnitServiceProxy,
        private _techDocServiceProxy: TechDocServiceProxy,
        private _equipmentServiceProxy: EquipmentServiceProxy,
        private _organizationUnitServiceProxy: OrganizationUnitServiceProxy
    ) {
        super(injector);
        this.selectPrimengTableHelper = new PrimengTableHelper();
    }
    ngOnInit () {
        this.getTabs();
     }
    show(taskId?: number): void {
        this.active = true;
        this.selected = [];
        this.selectPrimengTableHelper.records = this.selected;
        this.selectPrimengTableHelper.totalRecordsCount = 0;
        this._pipelineService.getPipelineTmpls().subscribe(result => {
            this.tmpls = result.items;

            // this.load()
        });

        this.modal.show();
    }
    getTabs() {
        this.tabs = [
            { label: '任务筛选', icon: 'fa fa-fw fa-bar-chart' , style : 1 },
            { label: '待批量任务反馈列表', icon: 'fa fa-fw fa-calendar', style : 2 },
            {label: '反馈工时', icon: 'fa fa-fw fa-calendar', style : 3}
        ];
    }
    tabTypeClick(tab: any, index) {
        this.index = index;
  }
    rowSelect(event: any) {
        let rowData = event.data;
        this._techDocServiceProxy
            .getTechDocForView(rowData.codeId)
            .subscribe(result => {
                this.techDocView = result;
            });
    }
    save(): void {
        let pipeLines = [];
        for (let i = 0; i < this.selected.length; i++) {
            pipeLines.push(this.selected[i].id);
        }
        this.addOther();
        let input = new BatchSetInput();
        input.pipeId = pipeLines;
        input.workers = this.setNodeWorkers;
        input.equipments = this.setNodeEquipments;
       // this.saving = true;
        this.saving = false;
        //this._pipelineService.getPipelineAndRunOfBatch(pipeLines)
        this._pipelineService.batchSet(input).subscribe(() => {
            this.notify.info('运行成功');
            this.close();
            this.modalSave.emit(null);
            this.modal.hide();
        });
    }
    close(): void {
        this.active = false;
        this.saving = false;
        this.primengTableHelper.records = null;
        this.filterText = '';
        this.selected = [];
        this.mainTaskGoProductionList = [];
        this.data = [];
        this.techDocs = new Array<SimpleTechDocDto>();
        this.techDocView = new TechDocDto();
        this.oldTechDocView = new TechDocDto();
        this.nodeWorker = new Array<GetNodeWorkOutput>();
        // this.nodeWorkerList = new Array<GetNodeWorkOutputOfBatch>();
        this.nodeWorker1 = new GetNodeWorkOutputOfBatch();
        // nodeWorker1 = new Array<GetNodeWorkOutputOfBatch>();
        this.setNodeWorkers = new SetNodeWorkersInput();
        this.setNodeWorkers1 = new Array<SetNodeWorkersInput>();
        this.pipeIds = [];
        this.pipeId = '';
        this.modal.hide();
       // this.getPipes();
        this.procInfo = new ProcViewDto();
    }

    getPipes(event?: LazyLoadEvent) {
        this._pipelineService
            .getPipelines(
                this.filterText,
                this.type,
                '58',
                '',
                undefined,
                undefined,
                this.primengTableHelper.getMaxResultCount(
                    this.paginator,
                    event
                ),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }

    //加入要投产的任务
    joinTask(pipe) {
        if (this.selected.length === 0) {
            if (pipe.actTypeName === '工序执行类') {
                this.selected.push(pipe);
                this.notify.success('当前任务加入成功');
            } else {
                this.notify.error('当前管道不能加入');
            }
        } else if (this.selected.length > 0) {
            for (let i = 0; i < this.selected.length; i++) {
                // let keepGoing = false;
                if (this.selected.indexOf(pipe) === -1) {
                    if (
                        pipe.id !== this.selected[i].id &&
                        pipe.actCode === this.selected[0].actCode
                     ) {
                        this.selected.push(pipe);
                        this.notify.success('当前任务加入成功');
                        break;
                    } else if (
                        pipe.id === this.selected[i].id ||
                        pipe.actCode !== this.selected[0].actCode
                    ) {
                        this.notify.error(
                            '当前管道和首选管道不属于同一节点或工艺规程,不能批量处理'
                        );
                    }
                } else {
                    this.notify.error('当前管道已添加');
                }
            }
        }
    }

    deletePipe(pipe) {
        for (let i = 0; i < this.selected.length; i++) {
            if (this.selected[i].id === pipe.id) {
                this.selected.splice(i, 1);
            }
        }

    }
    //获取要投产的任务列表
    getModels1() {
        this.selectPrimengTableHelper.records = this.selected;
        this.selectPrimengTableHelper.totalRecordsCount = this.selected.length;
        this.selectPrimengTableHelper.hideLoadingIndicator();
    }

    //反馈相关
    loadgw(pipes: Array<PipelineListDto>): void {
        this.pipes = pipes;
        this.pipeIds = [];
        let pipeNodeId = '';

        // this.nodeWorkerList = new Array<GetNodeWorkOutputOfBatch>();
        this.pipes.forEach(pipe => {
            this.pipeId = pipe.id;
            this.nodeWorker = new Array<GetNodeWorkOutput>();
            let nodeWorker1 = new GetNodeWorkOutputOfBatch();

            //let nodeWorkerList1 = new Array<GetNodeWorkOutputOfBatch>();
            this.pipeNodeId = pipe.nodeId;
            //this.reloadProcInfo();
            this.pipeIds.push(this.pipeId);

            nodeWorker1.pipelineNodeId = pipe.nodeId;
            nodeWorker1.pipelineId = pipe.id;

            // this.nodeWorkerList.push(nodeWorker1)
        });

        //设备信息
        this._taskServiceProxy
            .getNodeEquipments(this.pipes[0].nodeId)
            .subscribe(result => {
                this.equipments = result.items;
                this.selectshebei = new Array<ComboboxItemDto>();
                result.items.forEach(item => {
                    let com = new ComboboxItemDto();
                    com.displayText = item.displayName + '*' + item.code;
                    com.value = item.sysId;

                    this.selectshebei.push(com);
                    this._equipmentServiceProxy
                        .getEquipmentForPipeNode()
                        .subscribe(result => {
                            this.shebei = new Array<ComboboxItemDto>();
                            result.forEach(item => {
                                let com = new ComboboxItemDto();
                                com.displayText =
                                    item.equipName + '*' + item.code;
                                com.value = item.id.toString();
                                this.shebei.push(com);
                            });
                        });
                });
            });
        //获取工位
        this._taskServiceProxy.getStations('58').subscribe(result => {
            this.stations = result;

        });
        this._organizationUnitServiceProxy
            .findUsersForNode()
            .subscribe(result => {
                this.users = result;
            });
        this._equipmentServiceProxy
            .getEquipmentForPipeNode()
            .subscribe(result => {
                this.shebei = new Array<ComboboxItemDto>();
                result.forEach(item => {
                    let com = new ComboboxItemDto();
                    com.displayText = item.equipName + '*' + item.code;
                    com.value = item.id.toString();
                    this.shebei.push(com);
                });
            });
            this.notify.info('请开始反馈工时');
    }
    selectgw() {
        this.stations.forEach(el => {
            // tslint:disable-next-line:triple-equals
            if (this.stationId == el.id) {
                this.station = el;
            }
        });
    }

    showDialogToAdd() {
        // this.newCar = true;
        let selectedWork = new GetNodeWorkOutput();
        selectedWork.userName = new NameValueDto();
        selectedWork.userName = this.users[0];
        selectedWork.timePercentage = 100;
        this.nodeWorker.push(selectedWork);
    }

    addOther() {
        let nodeWorkers = new Array<NodeWorkerDto>();
        this.nodeWorker.forEach(item => {
            let nodeWorker = new NodeWorkerDto();
            nodeWorker.userId = Number(item.userName.value);
            nodeWorker.userName = item.userName.name;
            nodeWorker.timePercentage = item.timePercentage;
            nodeWorker.id = item.id;
            nodeWorker.nodeEntityId = this.pipe.nodeId;
            nodeWorker.pipelineEntityId = this.pipe.id;
            nodeWorkers.push(nodeWorker);
        });
        this.setNodeWorkers.workers = nodeWorkers;
        this.setNodeWorkers.nodeId = this.pipe.nodeId;
        this.setNodeWorkers.pipelineId = this.pipe.id;

        let nodeEquipments = new Array<NodeEquipmentDto>();
        this.selectshebei.forEach(item => {
            let nodeEquipment = new NodeEquipmentDto();
            nodeEquipment.sysId = item.value;
            nodeEquipment.nodeEntityId = this.pipe.nodeId;
            nodeEquipment.pipelineEntityId = this.pipe.id;
            nodeEquipment.displayName = item.displayText.split('*')[0];
            nodeEquipment.code = item.displayText.split('*')[1];
            this.equipments.forEach(eq => {
                if (
                    eq.code === nodeEquipment.code &&
                    eq.displayName === nodeEquipment.displayName
                ) {
                    nodeEquipment.id = eq.id;
                }
            });
            nodeEquipments.push(nodeEquipment);
        });
        this.setNodeEquipments.equipments = nodeEquipments;
        this.setNodeEquipments.nodeId = this.pipe.nodeId;
        this.setNodeEquipments.pipelineId = this.pipe.id;
    }
}
